package com.alexgaoyh.auth.servlet;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthServlet extends HttpServlet {

	public AuthServlet() {
		super();
	}

	/**
	 * 
	 * Destructionoftheservlet.<br>
	 */

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		DomainName = request.getSession().getServletContext().getInitParameter("DomainName");

		CookName = request.getSession().getServletContext().getInitParameter("CookieName");
		// ��֤��
		String location = request.getContextPath() + "/login.jsp";

		String username = request.getParameter("username");

		String userpassword = request.getParameter("userpassword");

		String key = accounts.get(username);

		if (key == null) {

			response.sendRedirect(location);

		} else {

			if (key.equals(userpassword)) {// ��֤ͨ��

				String gotoURL = request.getParameter("goto");

				String sessionId = request.getSession().getId();

				Cookie cookie = new Cookie(CookName, sessionId);

				cookie.setMaxAge(1000);

				cookie.setPath("/");

				response.addCookie(cookie);

				if (gotoURL != null) {

					response.sendRedirect(gotoURL);

				} else {

					response.sendRedirect(location);

				}

			} else {

				response.sendRedirect(location);

			}


		}

	}

	/**
	 * 
	 * Initializationoftheservlet.<br>
	 * 
	 * 
	 * 
	 * @throwsServletExceptionifanerroroccurs
	 */

	static private ConcurrentMap<String, String> accounts;

	// static private ConcurrentMap SSOIDs;

	String CookName;

	String DomainName;

	@Override
	public void init(ServletConfig config) throws ServletException {

		accounts = new ConcurrentHashMap<String, String>();

		accounts.put("admin", "admin");

	}
}
